package com.knight.hadoop.day12.zuoye;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang.ArrayUtils;

public class LogBeanParse {
	
	private static SimpleDateFormat format1 = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.US);
	private static SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static LogBean parse(String line){
		
		String[] values = line.split(" ");
		
		LogBean logBean = new LogBean();
		if (values.length >11) {
			String requestIP = values[0];// 194.237.142.21
			String remoteUser = "-";
			String requestDate = parseDate(values[3].substring(1));// [18/Sep/2013:06:49:18
			String requestMethod = values[5];// "GET
			String requestURL = values[6]; /// wp-content/uploads/2013/07/rstudio-git3.png
			String requestProtocol = values[7];// HTTP/1.0"
			String responseCode = values[8];// 200
			String responseDataSize = values[9];// 185524
			String requestSourcesURL = values[10].substring(1, values[10].length()-1);// "http://cos.name/category/software/packages/"
			Object[] subarray = ArrayUtils.subarray(values, 11, values.length);
			StringBuilder sb = new StringBuilder();
			if(subarray!=null && subarray.length>0){
				for(Object o:subarray){
					sb.append(o.toString());
				}
			}
			String tmp = sb.toString();
			if(tmp.length()>0){
				tmp = tmp.substring(1, tmp.length()-1);
			}
			String customerInfo = tmp;// {"Mozilla/5.0,(Windows,NT,6.1),AppleWebKit/537.36,(KHTML,,like,Gecko),Chrome/29.0.1547.66,Safari/537.36"}
			
			logBean.set(requestIP, remoteUser,responseCode, responseDataSize, requestDate,requestURL, requestSourcesURL,customerInfo);
			
			if(Integer.parseInt(responseCode)>=400){
				logBean.setValid(false);
			}
			if(requestURL!=null && (requestURL.contains(".png") || requestURL.contains(".gif") 
					|| requestURL.contains(".js") || requestURL.contains(".jpg") 
				    ||requestURL.contains(".css") || requestURL.contains(".ico"))){
				logBean.setValid(false);
			}
			
		}else{
			logBean.setValid(false);
		}
		return logBean; 
	}
	
	public static String parseDate(String date){
		Date parseDate = null;
		try {
			parseDate = format1.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return format2.format(parseDate);
	}
}
